// 链表栈

package main

import (
	"fmt"
	"sync"
)

// 链表队列
type LinkQueue struct {
	root *LinkNode
	size int
	lock sync.Mutex
}

// 链表节点
type LinkNode struct {
	next *LinkNode
	data string
}

// 将数据放入链表队列的末尾
func (queue *LinkQueue) Add(v string) {
	queue.lock.Lock()
	defer queue.lock.Unlock()

	newNode := new(LinkNode)
	newNode.data = v

	if queue.root == nil {
		queue.root = newNode
	} else {
		nowNode := queue.root
		for nowNode.next != nil {
			nowNode = nowNode.next
		}

		nowNode.next = newNode
	}

	queue.size++

}

// 取出链表队列头部的数据
func (queue *LinkQueue) Remove() string {
	queue.lock.Lock()
	defer queue.lock.Unlock()

	if queue.size == 0 {
		panic("没有数据")
	}

	preRootNode := queue.root
	queue.root = preRootNode.next

	queue.size--
	return preRootNode.data
}

// 获取链表队列的大小
func (queue *LinkQueue) Size() int {
	return queue.size
}

func (queue *LinkQueue) AllData() {
	queue.lock.Lock()
	defer queue.lock.Unlock()

	if queue.size == 0 {
		panic("没有数据")
	}

	nowNode := queue.root

	for nowNode != nil {
		fmt.Print(nowNode.data, "   ")
		nowNode = nowNode.next
	}
	fmt.Println()
}

func main() {
	linkQueue := new(LinkQueue)
	linkQueue.Add("Dog")
	fmt.Println("Size: ", linkQueue.Size())
	linkQueue.AllData()
	linkQueue.Add("Pig")
	fmt.Println("Size: ", linkQueue.Size())
	linkQueue.AllData()
	linkQueue.Add("Cat")
	fmt.Println("Size: ", linkQueue.Size())
	linkQueue.AllData()
	fmt.Println("Remove: ", linkQueue.Remove())
	fmt.Println("Size: ", linkQueue.Size())
	linkQueue.AllData()
}
